<template>
  <div class="verify-btn" :class="{ 'is-disabled': disabled }" @click="handleClick">
    {{ showText }}
  </div>
</template>

<script>
export default {
  name: 'vx-verify-code',
  data() {
    return {
      disabled: false,
      showText: '',
      seconds: 60,
    };
  },
  props: {
    defaultText: {
      type: String,
      default: '获取验证码',
    },
    handler: {
      type: Function,
    },
    formatText: {
      type: String,
      default: '{s}秒后重新获取',
    },
    time: {
      type: Number,
      default: 60,
    },
  },
  methods: {
    labelUpdate(curr) {
      this.showText = this.formatText.replace(/\{s\}/, curr);
    },
    labelReset() {
      this.showText = this.defaultText;
    },
    count() {
      this.disabled = true;
      var curr = this.seconds;
      this.labelUpdate(curr);
      var that = this; // 计时器会变更执行环境
      that.timer = setInterval(function() {
        // 计时器会变更执行环境
        if (curr < 2) {
          that.disabled = false;
          that.labelReset();
          curr = that.seconds;
          clearInterval(that.timer);
        } else {
          curr--;
          that.labelUpdate(curr);
        }
      }, 1000);
    },
    async handleClick() {
      if (this.disabled) return;
      var handler = this.handler;
      if (handler && typeof handler == 'function') {
        const result = await handler(this);
        if (result) {
          this.count();
        }
      } else {
        this.count();
      }
    },
  },
  mounted() {
    this.showText = this.defaultText;
    this.seconds = this.time || 60;
  },
  destroyed() {
    this.timer && clearInterval(this.timer);
  },
};
</script>

<style lang="scss">
.verify-btn {
  font-size: 14px;
  border: 1px solid $color-border-8;
  color: $color-primary;
  background: #fff;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 32px;
  border-radius: 4px;
  padding: 0 10px;
  cursor: pointer;
  &.is-disabled {
    color: #808591;
    border-color: #808591;
    cursor: default;
  }

  .verify-msg > span {
    color: #ff9e00;
  }
}
</style>
